package classes {
	import UIFree.uif_loader;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;

	public class c_plugins {
		public static const COMPLETEPLUGINS: String 		= 'COMPLETEPLUGINS';
		public static const COMPLETESTARTPLUGINS: String 	= 'COMPLETESTARTPLUGINS';
		
		private var _app			: EventDispatcher;
		private var _plugins		: Array;
		
		public function c_plugins(a_app: EventDispatcher, a_list: Array) {
			_app = a_app;
			assignList(a_list);
		}
		
		protected function assignList(a_list: Array): void {
			_plugins 				= new Array();
			var _completeWait: int	= 0;
			for (var i: int=0; i<a_list.length; i++) {
				c_util.loadPolicyFile(a_list[i].url);
				if (a_list[i].completeWait) _completeWait ++;
				var loader: uif_loader = new uif_loader(null, a_list[i].url, function(e: Event): void {
					var a_loader: uif_loader = e.target.loader;
					_plugins.push(a_loader);
					(a_loader.content as Object).initialize(_app);
					if (a_loader._data.completeWait) {
						_completeWait--;
						if (_completeWait == 0) completeStartPlugins();
					}
					if (_plugins.length == a_list.length) doComplete();
				}, 0, 0, new LoaderContext(true, ApplicationDomain.currentDomain, SecurityDomain.currentDomain));
				loader._data = a_list[i];
			}
			if (_completeWait == 0) completeStartPlugins();
		}
		
		protected function completeStartPlugins(): void {
			_app.dispatchEvent(new Event(COMPLETESTARTPLUGINS));
		}
		
		protected function doComplete(): void {
			_app.dispatchEvent(new Event(COMPLETEPLUGINS));
		}
		
		public function get list(): Array {
			return _plugins;
		}
	}
}